package com.jiemengshi.server.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jiemengshi.server.util.ApiHttp;
import com.jiemengshi.server.util.StringUtil;
import org.apache.http.HttpException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by MingQi on 2017/7/21.
 */
@Service
public class WechatThirdPartyService {
    private String wxAppId = "wxa268725624e9f60c";
    private String wxSecret = "356fc91104d93cae9fb76c5d743a60c2";

    private Cache tokenCache;
    
    @Autowired
    public WechatThirdPartyService(EhCacheCacheManager cacheManager) {
        tokenCache = cacheManager.getCache("token");
    }
    
    private String getAccessToken() throws HttpException, IOException {
        String key = "third-party-accessToken";

        String accessToken = tokenCache.get(key, String.class);
        if (!StringUtil.isEmpty(accessToken)) {
            return accessToken;
        }

        // 获取accessToken start
        String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                + wxAppId + "&secret=" + wxSecret;
        String responseJsonData = ApiHttp.doGet(accessTokenUrl);
        JSONObject jsonData = JSON.parseObject(responseJsonData);
        accessToken = jsonData.getString("access_token");

        if (!StringUtil.isEmpty(accessToken)) {
            tokenCache.put(key, accessToken);
        }

        return accessToken;
    }

    /**
     * 获取关注者的wechatOpenid
     * @param nextOpenid
     * @return
     */
    private List<String> getUserList(String nextOpenid) throws IOException, HttpException {
        // 通过网页获取用户信息
        String pullUserInfoUrl = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + getAccessToken() + "&next_openid=" + nextOpenid;
        String userListInfo = ApiHttp.doGet(pullUserInfoUrl);

        JSONObject data = JSON.parseObject(userListInfo);

        List<String> wechatOpenids = new ArrayList<String>();
        JSONArray openIds = data.getJSONObject("data").getJSONArray("openid");
        for (Object openId : openIds) {
            String openIdStr = (String)openId;
            if (!StringUtil.isEmpty(openIdStr)) {
                wechatOpenids.add(openIdStr);
            }
        }

        return wechatOpenids;
    }

    /**
     * 通过openId获得已经订阅公众号的用户昵称
     *
     * @param openId
     * @return
     * @throws IOException
     * @throws HttpException
     */
    private String getUserNickname(String openId) throws HttpException, IOException {
        String subscribeUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="
                + getAccessToken() + "&openid=" + openId + "&lang=zh_CN";
        String subscribeJsonData = ApiHttp.doGet(subscribeUrl);
        return JSON.parseObject(subscribeJsonData).getString("nickname");
    }

    public JSONArray getUserInfoList() throws IOException, HttpException {
        List<String> openIds = getUserList("");
        List<String> allOpenIds = new ArrayList<>(openIds);
        while (openIds.size() == 10000) {
            openIds  = getUserList(openIds.get(9999));
            for (String openId : openIds) {
                allOpenIds.add(openId);
            }
        }

        JSONArray ret = new JSONArray();
        for (String openId : allOpenIds) {
            JSONObject userInfo = new JSONObject();
            userInfo.put("openId", openId);
            userInfo.put("nickname", getUserNickname(openId));
            ret.add(userInfo);
        }
        return ret;
    }
}
